package cn.eng.pet.service.impl;

import cn.eng.basic.commonenum.ErrorCode;
import cn.eng.basic.domain.Point;
import cn.eng.basic.exception.BusinessException;
import cn.eng.basic.utils.*;
import cn.eng.order.domain.OrderPetAcquisition;
import cn.eng.order.dto.OrderDto;
import cn.eng.order.mapper.OrderPetAcquisitionMapper;
import cn.eng.org.domain.Employee;
import cn.eng.org.domain.Shop;
import cn.eng.org.mapper.EmployeeMapper;
import cn.eng.org.mapper.ShopMapper;
import cn.eng.pet.domain.SearchMasterMsg;
import cn.eng.pet.domain.SearchMasterMsgAuditLog;
import cn.eng.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.eng.pet.mapper.SearchMasterMsgMapper;
import cn.eng.pet.query.SearchMasterMsgQuery;
import cn.eng.pet.service.ISearchMasterMsgService;
import cn.eng.basic.service.impl.BaseServiceImpl;
import cn.eng.user.domain.Logininfo;
import cn.eng.user.domain.User;
import cn.eng.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import springfox.documentation.builders.BuilderDefaults;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 业务实现类：
 */
@Service
@SuppressWarnings("all")
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    /**
     * 发布寻主消息
     * @param searchMasterMsg
     * @param request
     * @return
     */
    @Override
    @Transactional
    public AjaxResult publish(SearchMasterMsg searchMasterMsg, HttpServletRequest request) throws Exception {
        //1.从请求里面 获取登录人的信息
        Logininfo logininfo = LoginContext.getLogininfo(request);
        //2. 把寻主的登录信息id设置给user-id
        searchMasterMsg.setUserId(logininfo.getId());
        searchMasterMsg.setState(0);
        //3. 把寻主消息添加到数据库
        searchMasterMsgMapper.save(searchMasterMsg);
        //使用百度智能审核
        Boolean textCensor = BaiduAuditUtils.TextCensor(searchMasterMsg.getName() + searchMasterMsg.getTitle());
        //审核通过
        if (textCensor){
            //修改状态 0 —— > 1（审核通过）
            searchMasterMsg.setState(1);
            //查询所有的可用的店铺
            List<Shop> shops = shopMapper.loadAvailableShop();
            //获取地址并解析地址
            Point point = DistanceUtils.getPoint(searchMasterMsg.getAddress());
            //使用工具类计算最近的地址
            Shop nearestShop = DistanceUtils.getNearestShop(point, shops);
            if (nearestShop == null){
                //没有靠近的店铺 就设置状态- 寻主池
                searchMasterMsg.setState(3);
            }else {
                //找到店铺 就设置店铺id 给寻主消息
                searchMasterMsg.setShopId(nearestShop.getId());
                //通过店铺关联的管理员  去查询 员工信息
                Employee employee = employeeMapper.loadById(nearestShop.getAdminId());
                //发送短信
                //SmsUtils.sendSms(employee.getPhone(),"你有新的订单，请在3天之内去【"+searchMasterMsg.getAddress()+"】接回宠物");
                System.out.println("你有新的订单，请在3天之内去【" + searchMasterMsg.getAddress() + "】接回宠物");
            }
            //更新一下searchMasterMsg信息
            searchMasterMsgMapper.update(searchMasterMsg);
            //添加日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(searchMasterMsg.getId());
            log.setState(1);
            log.setAuditTime(new Date());
            searchMasterMsgAuditLogMapper.save(log);
            return new AjaxResult();
        //审核不通过
        }else {
            searchMasterMsg.setState(-1);
            searchMasterMsgMapper.update(searchMasterMsg);
            //添加日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setState(0);
            log.setAuditTime(new Date());
            searchMasterMsgAuditLogMapper.save(log);
            return new AjaxResult().setSuccess(false).setMsg("审核不通过");
        }
    }

    /**
     * 用户查看自己的寻主消息
     * @param query
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query,HttpServletRequest request) throws Exception {
        //获取登录人的信息
        Logininfo logininfo = LoginContext.getLogininfo(request);
        //通过logininfoId查询user对象
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        //把用户对象的id设置到查询里面
        query.setUserId(user.getId());
        //使用super调用 同时返回
        return super.queryPage(query);
    }

    /**
     * 待处理
     * @param query
     * @param request
     * @return
     */
    @Override
    @Transactional
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) throws Exception {
        query.setState(1);
        //区分平台管理员或店铺管理员
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.loadByLogininfoId(logininfo.getId());
        if(employee.getShop_id() != null){//店铺管理员
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    /**
     * 已完成
     * @param query
     * @param request
     * @return
     */
    @Override
    @Transactional
    public PageList<SearchMasterMsg> finish(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(2);
        return super.queryPage(query);
    }

    /**
     * 寻主池
     * @param query
     * @param request
     * @return
     */
    @Override
    @Transactional
    public PageList<SearchMasterMsg> toSearchMasterPool(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(3);
        return super.queryPage(query);
    }

    /**
     * 拒单
     * @param id
     * @return
     */
    @Override
    @Transactional
    public AjaxResult reject(Long id) {
         searchMasterMsgMapper.reject(id);
        return AjaxResult.me();
    }

    /**
     * 接单
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public AjaxResult accept(OrderDto dto) {
        //判断是否已生成订单
        OrderPetAcquisition dborder = orderPetAcquisitionMapper.loadByMsgId(dto.getMsgId());
        if (dborder != null){
            if (dborder.getState() == 0){
                throw new BusinessException(ErrorCode.ORDER_ERROR.getCode());
            }
        }
        SearchMasterMsg msg = searchMasterMsgMapper.loadById(dto.getMsgId());
        //生成订单
        OrderPetAcquisition order = orderDto2Order(dto, msg);
        //添加到数据库
        orderPetAcquisitionMapper.save(order);
        //Employee employee = employeeMapper.loadById(orderDto.getHandler());//通过处理人的id, 获取处理人的信息
        //SmsUtils.sendSms(employee.getPhone(),"你有新的订单，请在3天内去"+order.getAddress()+"接回宠物");
        System.out.println("你有新的订单，请在3天内去"+order.getAddress()+"接回宠物");
        return AjaxResult.me();
    }
    /** 生成订单  -  需要依赖的方法 **/
    private OrderPetAcquisition orderDto2Order(OrderDto dto, SearchMasterMsg msg) {
        //创建一个OrderPetAcquisition对象
        OrderPetAcquisition order = new OrderPetAcquisition();
        //生成订单编号
        String sn = CodeGenerateUtils.generateOrderSn(msg.getUserId());
        order.setOrderSn(sn);
        order.setState(0);
        order.setDigest(dto.getNote());
        order.setLastcomfirmtime(new Date(System.currentTimeMillis()+3*24*60*60*1000));
        order.setPrice(msg.getPrice());
        order.setUserId(msg.getId());
        order.setShopId(msg.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(dto.getHandler());
        order.setSearchMasterMsgId(msg.getId());
        return order;
    }

}
